package com.asset.service.impl;

import com.asset.mapper.BrandMapper;
import com.asset.pojo.Brand;
import com.asset.service.BrandService;
import com.asset.util.AssetExceptionEnum;
import com.asset.util.AssetManageException;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 11725
 */
@Slf4j
@Service
public class BrandServiceImpl implements BrandService {

    @Resource
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> selectByPage(Integer page, Integer rows, Boolean selectAll) {
        if (selectAll == null) {
            // 允许分页
            PageHelper.startPage(page, rows);
        }

        List<Brand> brandList = brandMapper.selectAll();
        if (CollectionUtils.isEmpty(brandList)) {
            throw new RuntimeException("未找到匹配的品牌集合");
        }

        PageInfo<Brand> info = new PageInfo<>(brandList);

        return new PageResult<>(info.getTotal(), brandList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(Brand brand) {
        brand.setId(null);
        brandMapper.insertSelective(brand);
    }

    @Override
    public Brand selectById(Long id) {
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null) {
            throw new AssetManageException(AssetExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }
}
